<template>
	<view class="registerView">
		<!-- 基础表单校验 -->
		<uni-forms ref="registerForm" :rules="rules" v-model="registerFormData">
			<uni-forms-item class="loginBottom" :label-width="labelWidth" label-align="right" label="公司名称" required
				name="comp_name">
				<input class="uni-input" v-model="registerFormData.comp_name" placeholder="请输入公司名称" />
			</uni-forms-item>
			<uni-forms-item class="loginBottom" :label-width="labelWidth" label-align="right" label="门店名称" required
				name="store_name">
				<input class="uni-input" v-model="registerFormData.store_name" placeholder="请输入门店名称" />
			</uni-forms-item>
			<uni-forms-item class="loginBottom country" :label-width="labelWidth" label-align="right" label="省/市/区" name=""
				required>
				<uni-data-picker :border="false" :localdata="items" placeholder="请选择" popup-title="请选择所在地区"
					@change="onchange">
				</uni-data-picker>
			</uni-forms-item>
			<uni-forms-item class="loginBottom" :label-width="labelWidth" label-align="right" label="具体地址" required
				name="store_adr">
				<input class="uni-input" v-model="registerFormData.store_adr" placeholder="请输入具体地址" />
				<!-- <textarea auto-height v-model="registerFormData.aaa" placeholder="" /> -->
			</uni-forms-item>
			<uni-forms-item class="loginBottom" :label-width="labelWidth" label-align="right" label="公司成立日期"
				name="comp_found_date" required>
				<picker mode="date" :value="registerFormData.comp_found_date" @change="bindDateChange">
					<!-- <view class="uni-input">{{registerFormData.comp_found_date}}</view> -->
					<input class="uni-input" v-model="registerFormData.comp_found_date" placeholder="请选择日期"
						disabled="" />
				</picker>
			</uni-forms-item>
			<uni-forms-item class="loginBottom" :label-width="labelWidth" label-align="right" label="法人姓名" required
				name="legal_name">
				<input class="uni-input" v-model="registerFormData.legal_name" placeholder="请输入姓名" />
			</uni-forms-item>
			<uni-forms-item class="loginBottom" :label-width="labelWidth" label-align="right" label="法人身份证号" required
				name="legal_id">
				<input class="uni-input" v-model="registerFormData.legal_id" placeholder="请输入身份证号" />
			</uni-forms-item>


			<view class="uni-form-item uni-column">
				<view class="title"><text class="uni-form-item__title required">营业执照</text></view>
				<view class="uni-input-wrapper">
					<uni-file-picker limit="1" title=" " fileMediatype="image" mode="grid" file-extname="jpeg,jpg,png"
						@select="selectImg(...arguments,'file_business_licenses')"
						@delete="deleteImg(...arguments,'file_business_licenses')"></uni-file-picker>
				</view>
			</view>
			<view class="uni-form-item uni-column">
				<view class="title"><text class="uni-form-item__title required">身份证正反面（主要负责人）</text></view>
				<view class="uni-input-wrapper">
					<uni-file-picker limit="2" title=" " fileMediatype="image" mode="grid" file-extname="jpeg,jpg,png"
						@select="selectImg(...arguments,'file_main_person_id')"
						@delete="deleteImg(...arguments,'file_main_person_id')">
					</uni-file-picker>
				</view>
			</view>
			<view class="uni-form-item uni-column">
				<view class="title"><text class="uni-form-item__title required">经营场地（合影+招牌）</text></view>
				<view class="uni-input-wrapper">
					<uni-file-picker limit="3" title=" " fileMediatype="image" mode="grid" file-extname="jpeg,jpg,png"
						@select="selectImg(...arguments,'file_business_premises_groupphoto')"
						@delete="deleteImg(...arguments,'file_business_premises_groupphoto')">
					</uni-file-picker>
				</view>
			</view>
			<view class="uni-form-item uni-column">
				<view class="title"><text class="uni-form-item__title required">经营场地（车位）</text></view>
				<view class="uni-input-wrapper">
					<uni-file-picker limit="3" title=" " fileMediatype="image" mode="grid" file-extname="jpeg,jpg,png"
						@select="selectImg(...arguments,'file_business_premises_carport')"
						@delete="deleteImg(...arguments,'file_business_premises_carport')">
					</uni-file-picker>
				</view>
			</view>
			<view class="uni-form-item uni-column">
				<view class="title"><text class="uni-form-item__title required">租赁合同</text></view>
				<view class="uni-input-wrapper">
					<uni-file-picker limit="3" title=" " fileMediatype="image" mode="grid" file-extname="jpeg,jpg,png"
						@select="selectImg(...arguments,'file_leasing_contract')"
						@delete="deleteImg(...arguments,'file_leasing_contract')">
					</uni-file-picker>
				</view>
			</view>
			<view class="uni-form-item uni-column">
				<view class="title"><text class="uni-form-item__title">经营场地（办公室）</text></view>
				<view class="uni-input-wrapper">
					<uni-file-picker limit="3" title=" " fileMediatype="image" mode="grid" file-extname="jpeg,jpg,png"
						@select="selectImg(...arguments,'file_business_office')"
						@delete="deleteImg(...arguments,'file_business_office')">
					</uni-file-picker>
				</view>
			</view>
			<view class="uni-form-item uni-column">
				<view class="title"><text class="uni-form-item__title">其他</text></view>
				<view class="uni-input-wrapper">
					<uni-file-picker limit="3" title=" " fileMediatype="image" mode="grid" file-extname="jpeg,jpg,png"
						@select="selectImg(...arguments,'file_business_other')"
						@delete="deleteImg(...arguments,'file_business_other')">
					</uni-file-picker>
				</view>
			</view>


			<uni-forms-item class="loginBottom" :label-width="labelWidth" label-align="right" label="使用者姓名" required
				name="user_name">
				<input class="uni-input" v-model="registerFormData.user_name" placeholder="请输入使用者姓名" />
			</uni-forms-item>
			<uni-forms-item class="loginBottom" :label-width="labelWidth" label-align="right" label="使用者手机号" required
				name="mobile">
				<input class="uni-input" v-model="registerFormData.mobile" placeholder="请输入使用者手机号" type="number" />
			</uni-forms-item>
			<uni-forms-item class="loginBottom" :label-width="labelWidth" label-align="right" label="验证码" required
				name="verify_code">
				<input class="uni-input" v-model="registerFormData.verify_code" maxlength="6" placeholder="请输入验证码" type="number" />
				<span class="verifyCodeBtn" @click="getVerifyCode()">{{countDownData ? countDownData + 's':'获取'}}</span>
			</uni-forms-item>

		</uni-forms>
		<button class="reginsterSubmit" type="primary" @click="submit('registerForm')">提交</button>
	</view>
</template>

<script>
	import {
		carMarketRegVerifyCode,
		carMarketRegFileUrl,
		carMarketRegSubmit
	} from '../../api/carMarketReg/index.js'; //引入需要的api

	import {
		fileToBase64,
		appfileToBase64
	} from '../../common/util.js'
	import list from './data.js' //省市区数据

	export default {
		data() {
			return {
				labelWidth: 110,
				items: list.list,
				// 校验表单数据
				registerFormData: {
					"api_key": getApp().globalData.api_key,
					"comp_name": "", //公司名称
					"store_name": "", //门店名称
					"province": "", //省
					"city": "", //市
					"district": "", //区
					"store_adr": "", //具体地址
					"comp_found_date": "", //公司成立日期
					"legal_name": "", //法人姓名
					"legal_id": "", //法人身份证号
					"user_name": "", //使用者姓名
					"mobile": "", //使用者手机号
					"verify_code": "", //短信验证码
				},
				img: {
					"file_business_licenses": [], //营业执照
					"file_main_person_id": [], //身份证
					"file_business_premises_groupphoto": [], //经营场地（合影+招牌）
					"file_business_premises_carport": [], //经营场地（车位）
					"file_leasing_contract": [], //租赁合同
					"file_business_office": [], //经营场地（办公室）
					"file_business_other": [], //其他	
				},
				imgToBase: {
					"file_business_licenses": [], //营业执照
					"file_main_person_id": [], //身份证
					"file_business_premises_groupphoto": [], //经营场地（合影+招牌）
					"file_business_premises_carport": [], //经营场地（车位）
					"file_leasing_contract": [], //租赁合同
					"file_business_office": [], //经营场地（办公室）
					"file_business_other": [], //其他	
				},
				imgData: {},
				countDownData: 0,
				// 校验规则
				rules: {
					comp_name: {
						rules: [{
							required: true,
							errorMessage: ' ',
							// errorMessage: '公司名称不能为空'
						}]
					},
					store_name: {
						rules: [{
							required: true,
							errorMessage: ' ',
							// errorMessage: '门店名称不能为空'
						}]
					},
					store_adr: {
						rules: [{
							required: true,
							errorMessage: ' ',
							// errorMessage: '详细地址不能为空'
						}]
					},
					comp_found_date: {
						rules: [{
							required: true,
							errorMessage: ' ',
							// errorMessage: '公司成立日期不能为空'
						}]
					},
					legal_name: {
						rules: [{
							required: true,
							errorMessage: ' ',
							// errorMessage: '法人姓名不能为空'
						}]
					},
					legal_id: {
						rules: [{
							required: true,
							errorMessage: ' ',
							// errorMessage: '法人身份证号不能为空'
						}]
					},
					user_name: {
						rules: [{
							required: true,
							errorMessage: ' ',
							// errorMessage: '使用者姓名不能为空'
						}]
					},
					mobile: {
						rules: [{
							required: true,
							errorMessage: ' ',
							// errorMessage: '使用者手机号不能为空'
						}]
					},
					verify_code: {
						rules: [{
							required: true,
							errorMessage: ' ',
							// errorMessage: '短信验证码不能为空'
						}]
					}
				}
			}
		},
		methods: {
			// 日期改变
			bindDateChange: function(e) {
				this.registerFormData.comp_found_date = e.detail.value
			},
			// 获取上传图片file
			selectImg(e, type) {

				let _this = this
				e.tempFiles.forEach((item, index) => {
					// #ifdef H5|MP-WEIXIN
					fileToBase64(item.file, function(dataurl) {
						_this.imgToBase[type].push({
							'uuid': item.uuid,
							'extname': item.extname,
							'base64': dataurl.replace(
								`data:image/${item.extname=="png"?"png":"jpeg"};base64,`,
								"")
						})
					})
					// #endif
					// #ifdef APP|APP-PLUS
					appfileToBase64(e.tempFilePaths[index], function(dataurl) {
						_this.imgToBase[type].push({
							'uuid': item.uuid,
							'extname': item.extname,
							'base64': dataurl.replace(
								`data:image/${item.extname=="png"?"png":"jpeg"};base64,`,
								"")
						})
					})
					// #endif
				})
				this.img[type] = this.img[type].concat(e.tempFiles)
			},
			// 删除图片
			deleteImg(e, type) {
				this.img[type] = this.img[type].filter(item => e.tempFile.uuid != item.uuid)
				this.imgToBase[type] = this.imgToBase[type].filter(item => e.tempFile.uuid != item.uuid)
			},
			// 校验图片
			validImg() {
				return (this.arrLength(this.img.file_business_licenses) == 1 &&
					this.arrLength(this.img.file_main_person_id) == 2 &&
					this.arrLength(this.img.file_business_premises_groupphoto) > 0 &&
					this.arrLength(this.img.file_business_premises_carport) > 0 &&
					this.arrLength(this.img.file_leasing_contract) > 0)
			},
			// 处理图片数据
			handleImgData() {
				let _this = this;
				// _this.imgToBase = {}
				// for (let key in _this.img) {
				// 	_this.imgToBase[key] = []
				// 	_this.imgToBase[key + '_suffix'] = []
				// 	_this.img[key].forEach((item, index) => {
				// 		_this.imgToBase[key + '_suffix'].push(item.extname)
				// 	})
				// }
				this.imgData = {
					"file_business_licenses": [], //营业执照
					"file_main_person_id": [], //身份证
					"file_business_premises_groupphoto": [], //经营场地（合影+招牌）
					"file_business_premises_carport": [], //经营场地（车位）
					"file_leasing_contract": [], //租赁合同
					"file_business_office": [], //经营场地（办公室）
					"file_business_other": [], //其他	
				}
				for (let key in this.imgData) {
					_this.imgData[key] = []
					_this.imgData[key + '_suffix'] = []
					_this.imgToBase[key].forEach((item, index) => {
						// 处理图片营业执照数据
						if (key == 'file_business_licenses') {
							_this.imgData["file_business_license"] = item.base64
							_this.imgData["file_business_license_suffix"] = item.extname
						} else {
							_this.imgData[key].push(item.base64)
							_this.imgData[key + '_suffix'].push(item.extname)
						}
					})
				}

			},
			// 倒计时函数
			countDown() {
				let _this = this
				_this.countDownData = 60
				let timer = setInterval(function() {
					_this.countDownData--;
					if (_this.countDownData == 0) {
						clearInterval(timer);
					}
				}, 1000);
			},
			// 获取省市区的数据
			onchange(e) {
				let arr = ["province", "city", "district"],
					_this = this
				// e.detail.value.forEach((item, index) => _this.registerFormData[arr[index]] = item.text)
				if (e.detail.value.length == 2) {
					_this.registerFormData[arr[0]] = _this.registerFormData[arr[1]] = e.detail.value[0].text
					_this.registerFormData[arr[2]] = e.detail.value[1].text
				} else if (e.detail.value.length == 3) {
					e.detail.value.forEach((item, index) => _this.registerFormData[arr[index]] = item.text)
				}
			},
			// 获取验证码
			getVerifyCode() {
				if (this.countDownData) {
					return uni.showModal({
						content: `请在${this.countDownData}秒后重试`,
						showCancel: false
					})
				}
				if (!/^1\d{10}$/.test(this.registerFormData.mobile)) {
					return uni.showModal({
						content: '手机号码填写错误',
						showCancel: false
					})
				}
				this.countDown()
				let obj = {
					mobile: this.registerFormData.mobile,
					api_key: getApp().globalData.api_key
				}
				// 获取短信验证码
				this.carMarketRegVerifyCodeApi(obj)
			},
			// 表单提交
			submit(ref) {
				let _this = this
				// 校验图片的完整性
				if (!this.validImg()) {
					return uni.showModal({
						content: "图片未上传完整",
						showCancel: false
					})
				}
				// 图片数据转base64
				this.handleImgData()

				// 校验省市区
				if (this.registerFormData.province == '') {
					return uni.showModal({
						content: "请选择省市区",
						showCancel: false
					})
				}
				// 校验表单完整性
				this.$refs[ref].validate().then(res => {
					// uni.showToast({
					// 	title: `校验通过`
					// })
					// setTimeout(function() {
					_this.carMarketRegSubmitApi({
						..._this.registerFormData,
						..._this.imgData,

						// // 处理图片营业执照数据
						// ...{
						// 	"file_business_license": _this.imgData.file_business_licenses[0],
						// 	"file_business_license_suffix": _this.imgData
						// 		.file_business_licenses_suffix[0]
						// }
					})
					// }, 5000)
				}).catch(err => {
					console.log(err)
					uni.showModal({
						content: "请填写完整再次提交！",
						showCancel: false
					})
				})
			},
			// isNullArr(name) {
			// 	return name.length == 0
			// },
			// isNullObj(name) {
			// 	return JSON.stringify(name) == "{}"
			// },
			// isNullStr(name) {
			// 	return name == ""
			// },
			// 获取数组长度
			arrLength(arr) {
				return arr.length
			},
			// 获取短信验证码
			carMarketRegVerifyCodeApi(data) {
				uni.showToast({
					title: '发送成功'
				});
				carMarketRegVerifyCode(data).then(res => {}).catch(err => console.log(err));
			},
			// 获取注册图片url
			carMarketRegFileUrlApi(data) {
				carMarketRegFileUrl(data).then(res => {
					console.log(res);
				}).catch(err => console.log(err));
			},
			// 提交注册
			carMarketRegSubmitApi(data) {
				carMarketRegSubmit(data).then(res => {
					uni.showModal({
						title: '提交成功',
						content: '审核通过后，会以短信形式通知您，注意查收！',
						btn: ["知道了"],
						success: function(res) {
							// if (res.confirm) {
							// 	console.log('用户点击确定');
							// } else if (res.cancel) {
							// 	console.log('用户点击取消');
							// }
							uni.navigateTo({
								url: '../'
							})
						}
					});
				}).catch(err => console.log(err));
			}
		}
	}
</script>

<style scoped>
	.required ::before {
		content: "*";
		color: red;
	}

	.registerView>>>.uni-forms-item__label .label-text {
		color: #000000;
		font-size: 16px;
	}

	.registerView>>>.uni-forms-item__inner {
		padding-bottom: 4px;
	}

	.registerView {
		padding: 20rpx;
	}

	.verifyCodeBtn {
		position: absolute;
		right: 0;
		top: 10px;
		cursor: pointer;
		color: #007AFF;
	}

	.loginBottom {
		border-bottom: 1px solid #ddd;
	}

	.reginsterSubmit {
		margin: 40upx;
	}
	
	.country {
		height: 80rpx;
	}
	
	.country>>>.input-value {
		font-size: 28rpx;
		padding-left: 26rpx;
	}
</style>
